%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     网络后台调用
%%% @end
%%%-------------------------------------------------------------------
-module(net_http_web_handler).

-export([init/2]).

-include("common.hrl").
-include("env.hrl").


init(Req, Opts) ->
    {ok, PostVals, Req2} = cowboy_req:read_urlencoded_body(Req),
    CallData = proplists:get_value(<<"call_data">>, PostVals),

    case CallData of
        undefined ->
            resp_failed(Req2, Opts, "call_data empty");
        _ ->
            try
                {ok, {Module, Func, Args, Time, Sign}} = util_type:bitstring_to_term(CallData),
                Handler = env_mgr:get(?ENV_NET_WEB_HANDLER),
                Result = Handler:handle(Module, Func, Args, Time, Sign),
                resp_success(Req2, Opts, Result)
            catch _:_:Stacktrace ->
                ?ERR("call_data invalid:~p", [Stacktrace]),
                resp_failed(Req2, Opts, "call_data invalid")
            end
    end.


resp_success(Req, Opts, Data) ->
    Req2 = cowboy_req:reply(200, #{ <<"content-type">> => <<"application/json; charset=utf-8">>}, Data, Req),
    {ok, Req2, Opts}.

resp_failed(Req, Opts, Msg) ->
    Req2 = cowboy_req:reply(200, #{<<"content-type">> => <<"application/json; charset=utf-8">>}, jsx:encode([{code, 1}, {msg, Msg}]), Req),
    {ok, Req2, Opts}.
